package com.xmall.order.handler.msg;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.xmall.config.AmqpCommonConfig;
import com.xmall.define.constants.CommonProperties;
import com.xmall.msg.queue.OrderModule;
import com.xmall.msg.entity.order.OrderPaySuccessMsg;
import com.xmall.order.entity.OrderPaySuccessRetryLog;
import com.xmall.order.service.IOrderPaySuccessRetryLogService;
import com.xmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * 订单支付成功
 */
@Slf4j
@Component
@RabbitListener(queues = OrderModule.OrderPaySuccess.ORDER_PAY_SUCCESS_QUEUE, containerFactory = AmqpCommonConfig.RABBIT_LISTENER_CONTAINER_FACTORY_NAME)
public class OrderPaySuccessHandler {

    @Resource
    private IOrderPaySuccessRetryLogService orderPaySuccessRetryLogService;

    @Resource
    private IOrderService orderService;

    @Resource
    private CommonProperties commonProperties;

    @RabbitHandler
    public void msg(Channel channel, Message message, OrderPaySuccessMsg msg) throws IOException {
        log.info("rabbitmq handler: order service: OrderPaySuccessHandler: {}", JSONUtil.toJsonStr(msg));
        OrderPaySuccessRetryLog log = new OrderPaySuccessRetryLog();
        log.setOrderId(msg.getOrderId());
        log.setTradeNo(msg.getTradeNo());
        log.setPayTime(msg.getPayTime());
        log.setPayType(msg.getPayType());
        log.setPayPlatform(msg.getPayPlatform());
        log.setCreateTime(new Date());
        log.setNextRetryTime(DateUtil.offsetSecond(new Date(), commonProperties.getLogRetryIntervalSecondsList().get(0)));
        orderPaySuccessRetryLogService.saveDuplicate(log);
        try {
            orderService.paySuccess(log);
        }catch (Exception e) {}
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
